package com.xuecheng.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.model.response.ResultCode;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * @Description: 异常统一捕获处理类
 * @Param:
 * @return:
 * @Author: Mr.Yuan
 * @Date:
 */
@ControllerAdvice
public class CustomExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomExceptionCatch.class);

    //捕获自定义异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult catchCustomException(CustomException customException) {
        ResultCode resultCode = customException.getResultCode();
        resultCode.message();
        LOGGER.error(customException.getMessage());
        return new ResponseResult(resultCode);
    }

    //    捕获系统运行时异常
//    定义map集合定义异常信息与响应码的映射，存储异常信息与响应码 ImmutableMap一旦创建不可改变，线程安全
    public static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    //    定义集合，存放异常类型与响应码的异常
   protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
    static {
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALIDPARAM);
        builder.put(HttpRequestMethodNotSupportedException.class,CommonCode.RequestMethodNotSupported);
        builder.put(MethodArgumentTypeMismatchException.class,CommonCode.MethodArgumentTypeMismatchException);
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseResult catchRunTimeException(Exception e) {

        LOGGER.error(e.getMessage());

        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        final ResultCode resultCode = EXCEPTIONS.get(e.getClass());
        final ResponseResult responseResult;
        if (resultCode == null) {

            return new ResponseResult(CommonCode.SERVER_ERROR);
        } else {
            return new ResponseResult(resultCode);
        }

    }
}
